package br.com.fogas.medicao.tabs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class TabHostHelper {

	private Map<String, TabsInfo> abas;
	
	private List<Fragment> fragments;
	
	private TabHost tabHost;
	
	public TabHostHelper(TabHost tabHost) {
		this.tabHost = tabHost;
		this.abas = new HashMap<String, TabsInfo>();
		this.fragments = new ArrayList<Fragment>();
	}
	
	public void destroyFragments() {
		for(Fragment fragment: fragments) {
			FragmentManager manager = fragment.getFragmentManager();
		    FragmentTransaction trans = manager.beginTransaction();
		    trans.remove(fragment);
		    trans.commit();
		}
	}
	
	public void criarAba(int position, String tag, String label, Fragment fragment) {
		TabsInfo tabsInfo = new TabsInfo(position, tag, label, fragment);
		abas.put(tabsInfo.getTag(), tabsInfo);
		fragments.add(tabsInfo.getFragment());
		newTabItem(tabsInfo);
	}
	
	public void newTabItem(TabsInfo tabsInfo) {
		TabSpec tabSpec = tabHost.newTabSpec(tabsInfo.getTag()).setIndicator(tabsInfo.getLabel());
		TabsFactory tabsFactory = new TabsFactory(tabHost.getContext());
		tabSpec.setContent(tabsFactory);
		tabHost.addTab(tabSpec);
	}
	
	public Map<String, TabsInfo> getAbas() {
		return abas;
	}
	
	public List<Fragment> getFragments() {
		return fragments;
	}
}